package com.ht.baselibs.services;

import android.app.IntentService;
import android.content.Intent;
import android.os.Environment;

import com.ht.baselibs.api.BaseLibApi;
import com.ht.baselibs.constant.FileConfig;
import com.ht.baselibs.core.EventCenter;
import com.ht.baselibs.core.EventCode;
import com.ht.baselibs.retrofit.converter.fastjson.FastJsonConverterFactory;
import com.ht.baselibs.retrofit.progress.DownloadProgressHandler;
import com.ht.baselibs.retrofit.progress.ProgressHelper;
import com.ht.baselibs.utils.FileUtils;
import com.ht.baselibs.utils.MD5Utils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.TimeUnit;

import de.greenrobot.event.EventBus;
import okhttp3.OkHttpClient;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Response;
import retrofit2.Retrofit;

/**
 * Created by huangtao on 16/7/14.
 */
public class DownloadApkSevice extends IntentService {

    public static final String APK_URL = "apk_url";
    public static final String APK_VERSION = "apk_version";
    public static final String APK_FILE_NAME = "new.apk";
    private int mOldProgress;
//    private NotificationManager mNotificationManager;
//    private NotificationCompat.Builder mBuilder;
//    private static final int notifyId = 100;




    public DownloadApkSevice() {
        super("com.ht.baselibs.services.DownloadApkSevice");
    }


    @Override
    public void onCreate() {
        super.onCreate();
//        mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
//        mBuilder = new NotificationCompat.Builder(getApplicationContext());
//        mBuilder.setWhen(System.currentTimeMillis())
//                .setSmallIcon(R.mipmap.notification_download)
//                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.notification_download))
//                .setContentTitle("正在下载")
//                .setProgress(100, 0, false)
//                .setTicker("开始下载");
//
//        Notification notification = mBuilder.build();
//        mNotificationManager.notify(notifyId, notification);
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        String apkUrl = intent.getStringExtra(APK_URL);
        String apkVersion = intent.getStringExtra(APK_VERSION);
        File parentFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + FileConfig.BASE_APK_FILE_DIR + getPackageName() +"/"+ MD5Utils.encode(apkVersion));

        if (!parentFile.exists()){
            parentFile.mkdirs();
        }

        Retrofit.Builder retrofitBuilder = new Retrofit.Builder();
        OkHttpClient.Builder builder = ProgressHelper.addProgress(null)
                .connectTimeout(20, TimeUnit.SECONDS)
                .readTimeout(20, TimeUnit.SECONDS);
        BaseLibApi retrofit = retrofitBuilder
                .client(builder.build())
                .baseUrl("http://test.com") //这里的baseUrl不用设置
                .addConverterFactory(FastJsonConverterFactory.create())
                .build()
                .create(BaseLibApi.class);

        ProgressHelper.setProgressHandler(new DownloadProgressHandler() {
            @Override
            protected void onProgress(long bytesRead, long contentLength, boolean done) {
//                int progress = (int) ((100 * bytesRead) / contentLength);
//                mBuilder.setContentTitle("正在下载")
//                        .setContentText(String.format("%d%% done\n", progress))
//                        .setProgress(100, progress, false);
//                Notification notification = mBuilder.build();
//                mNotificationManager.notify(notifyId, notification);
                int progress = (int) (1.0 * bytesRead * 100 / contentLength);
                if (progress != mOldProgress){
                    mOldProgress = progress;
                    EventBus.getDefault().post(new EventCenter(EventCode.EVENT_CODE_UPDATE_APK_PROGRESS, progress));
                }
            }
        });

        Call<ResponseBody> downloadApkCall = retrofit.downloadApk(apkUrl);
        try {
            Response<ResponseBody> response = downloadApkCall.execute();
            if (response.isSuccessful()){
                InputStream inputStream = response.body().byteStream();
                File file = new File(parentFile, APK_FILE_NAME);
                FileUtils.inputStream2File(inputStream, file);
                EventBus.getDefault().post(new EventCenter(EventCode.EVENT_CODE_UPDATE_APK_END, file.getAbsolutePath()));
            }else {
                EventBus.getDefault().post(new EventCenter(EventCode.EVENT_CODE_UPDATE_APK_ERROR));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
